package com.watson.ftp.demo;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

import static com.watson.ftp.demo.FtpConfig.*;

/**
 * @Author watson
 * @Date 2022/6/13 16:10
 * @Description: TODO
 * @Version 1.0
 */
public class Test {
    private static final Logger logger = LoggerFactory.getLogger(Test.class);
    /**
     * FTP 基础路径(根目录)
     */
    public static String basePath1 = "/aaaaaaa/bbb/ccccccc";

    /**
     * Description: 向FTP服务器上传文件
     *
     * @param filePath FTP服务器文件存放路径。例如分日期存放：/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input    本地要上传的文件的 输入流
     * @return 成功返回true，否则返回false
     */
    public static boolean uploadFile(String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {

            boolean ftpConnectB = ftpConnect(ftp);
            if (!ftpConnectB) {
                return result;
            }

            //中文
            String basePath = new String(basePath1.getBytes(LOCAL_CHARSET), SERVER_CHARSET);

            filePath = new String(filePath.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
            filename = new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET);

            String tempPath = "";
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) {
                        continue;
                    }
                    tempPath += File.separator + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(dir)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }

            //上传文件
            if (!ftp.storeFile(filename, input)) {
                logger.info(" --- ftp上传失败 --- ");
                return result;
            }

            logger.info(" --- ftp上传结束 --- ");
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            logger.info("上传文件过程发生错误" + e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.info("关闭连接过程发生异常" + ioe);
                }
            }
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param localPath  下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String remotePath, String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            boolean ftpConnectB = ftpConnect(ftp);
            if (!ftpConnectB) {
                return result;
            }

            //中文
            remotePath = new String(remotePath.getBytes(LOCAL_CHARSET), SERVER_CHARSET);

            boolean localPathBoolean = pathExist(localPath, true);
            if (!localPathBoolean) {
                logger.info(" --- ftp下载生成目录错误 --- ");
                return result;
            }

            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + File.separator + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    //中文
                    String ffName = new String(ff.getName().getBytes(LOCAL_CHARSET), SERVER_CHARSET);
                    ftp.retrieveFile(ffName, is);
                    is.close();
                }
            }

            logger.info(" --- ftp下载结束 --- ");
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    public static boolean pathExist(String localPath, boolean flag) {
        File file = new File(localPath);
        if (!file.exists()) {
            return false;
        } else {
            return true;
        }

    }


    public static void main(String[] args) throws FileNotFoundException {
        InputStream inputStream = new InputStream() {
            @Override
            public int read() throws IOException {
                return 0;
            }
        };

    }
}
